package Middleware

import (
	"hyper/supports/helpers"
	"net/http"

	"github.com/gin-gonic/gin"

	"hyper/supports/cryption"
	"hyper/supports/response"
	"hyper/supports/utils"
)

var rsaRoute = map[string]bool{
	"/admin/outLogin":    true,
	"/admin/createOrder": true,
}

// 所有POST 提交全部加密 再这里处理参数 以及判断参数是否合法
func ParamMiddleware(c *gin.Context) {

	// 如果为GET 请求直接放行
	if c.Request.Method == http.MethodGet {
		c.Next()
		return
	}

	if _, ok := rsaRoute[c.FullPath()]; ok {
		c.Next()
		return
	}

	data := map[string]any{}
	c.ShouldBindJSON(&data)

	// l := c.GetHeader("Accept-Language")

	// 参数不存在
	if len(data) < 1 {
		response.ResponseException(c, http.StatusOK, "参数不存在", nil)
		c.Abort()
		return
	}

	// 获取密钥
	prvKey, err := utils.GetPrivateKey()
	if err != nil {
		response.ResponseException(c, http.StatusOK, "密钥获取失败！", nil)
		c.Abort()
		return
	}

	// 解密参数
	newData, err := cryption.RsaDecrypt(data["data"].(string), prvKey)
	if err != nil {
		response.ResponseException(c, http.StatusOK, "解密失败！", nil)
		c.Abort()
		return
	}

	// json 转map
	m, err := helpers.JsonToMap(newData)
	if err != nil {
		response.ResponseException(c, http.StatusOK, "数据转换失败！", nil)
		return
	}

	// 设置上下文内 post 数据
	c.Set("params", m)
	c.Set("dataJson", newData)
	c.Next()
}
